from flask import Flask, render_template, jsonify, request
import json
from datetime import datetime, timedelta
import pandas as pd
from io import BytesIO

app = Flask(__name__)

# 任务数据文件
TASKS_FILE = 'tasks.json'

def load_tasks():
    """加载任务数据"""
    try:
        with open(TASKS_FILE, 'r', encoding='utf-8') as f:
            return json.load(f)
    except FileNotFoundError:
        # 默认任务数据
        return {
            "tasks": [
                # 技术研发组
                {"id": 1, "name": "实验室工艺优化", "start": "2026-01-01", "end": "2026-07-31", "group": 0, "progress": 0},
                {"id": 2, "name": "技术研发", "start": "2026-01-01", "end": "2026-10-31", "group": 0, "progress": 0},
                {"id": 3, "name": "产品化验证", "start": "2026-04-01", "end": "2027-01-31", "group": 0, "progress": 0},
                {"id": 4, "name": "市场拓展", "start": "2026-07-01", "end": "2027-04-30", "group": 0, "progress": 0},
                {"id": 5, "name": "运营管理", "start": "2026-10-01", "end": "2027-07-31", "group": 0, "progress": 0},
                {"id": 6, "name": "示范项目", "start": "2027-01-01", "end": "2027-10-31", "group": 0, "progress": 0},
                {"id": 7, "name": "实时监控", "start": "2027-04-01", "end": "2027-10-31", "group": 0, "progress": 0},
                {"id": 8, "name": "专利布局", "start": "2026-01-01", "end": "2026-10-31", "group": 0, "progress": 0},
                
                # 产线建设组
                {"id": 9, "name": "中试产线设计", "start": "2026-01-01", "end": "2026-06-30", "group": 1, "progress": 0},
                {"id": 10, "name": "设备采购", "start": "2026-03-01", "end": "2026-09-30", "group": 1, "progress": 0},
                {"id": 11, "name": "产线安装调试", "start": "2026-07-01", "end": "2026-12-31", "group": 1, "progress": 0},
                {"id": 12, "name": "试生产", "start": "2027-01-01", "end": "2027-06-30", "group": 1, "progress": 0},
                {"id": 13, "name": "产能爬坡", "start": "2027-04-01", "end": "2027-09-30", "group": 1, "progress": 0},
                {"id": 14, "name": "质量认证", "start": "2027-07-01", "end": "2027-12-31", "group": 1, "progress": 0}
            ],
            "groups": [
                {"id": 0, "name": "技术研发组", "color": "#3498db"},
                {"id": 1, "name": "产线建设组", "color": "#e74c3c"}
            ]
        }

def save_tasks(tasks_data):
    """保存任务数据"""
    with open(TASKS_FILE, 'w', encoding='utf-8') as f:
        json.dump(tasks_data, f, ensure_ascii=False, indent=2)

@app.route('/')
def index():
    """主页"""
    return render_template('index.html')

@app.route('/api/tasks')
def get_tasks():
    """获取所有任务"""
    return jsonify(load_tasks())

@app.route('/api/tasks/<int:task_id>', methods=['PUT'])
def update_task(task_id):
    """更新任务"""
    tasks_data = load_tasks()
    task_data = request.json
    
    for task in tasks_data['tasks']:
        if task['id'] == task_id:
            task.update(task_data)
            break
    
    save_tasks(tasks_data)
    return jsonify({'success': True})

@app.route('/api/export/excel')
def export_excel():
    """导出Excel"""
    tasks_data = load_tasks()
    df = pd.DataFrame(tasks_data['tasks'])
    
    # 添加组名
    group_map = {g['id']: g['name'] for g in tasks_data['groups']}
    df['group_name'] = df['group'].map(group_map)
    
    # 计算持续时间
    df['duration_days'] = (pd.to_datetime(df['end']) - pd.to_datetime(df['start'])).dt.days
    
    # 重命名列
    df = df.rename(columns={
        'name': '任务名称',
        'start': '开始日期',
        'end': '结束日期',
        'group_name': '所属组别',
        'progress': '进度(%)',
        'duration_days': '持续时间(天)'
    })
    
    # 选择需要的列
    df = df[['任务名称', '所属组别', '开始日期', '结束日期', '持续时间(天)', '进度(%)']]
    
    # 创建Excel文件
    output = BytesIO()
    with pd.ExcelWriter(output, engine='openpyxl') as writer:
        df.to_excel(writer, sheet_name='甘特图任务', index=False)
    
    output.seek(0)
    
    return output.getvalue(), 200, {
        'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'Content-Disposition': 'attachment; filename=甘特图任务.xlsx'
    }

if __name__ == '__main__':
    # 初始化任务文件
    if not os.path.exists(TASKS_FILE):
        save_tasks(load_tasks())
    
    app.run(debug=True, host='0.0.0.0', port=5000)
